import React from 'react';
import { Card, Table, Divider ,Modal, Button, Form, Input, Radio, Icon, message ,DatePicker,Pagination ,Upload ,Select,Spin,Tree } from 'antd';
import { NavLink} from 'react-router-dom';
import moment from 'moment';
import menuConfig from './../../../router/routerConfig';
import ResizeableTitle from './../../../utils/resizeableTitle';
import Utils from './../../../utils/utils';
import './../../../style/style.css';
import Axios from "../../../axios";
import {objectNoInfo, quickSelectKey} from "../../../config/systemConfig";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TextArea = Input.TextArea;
const TreeNode = Tree.TreeNode;

export default class Role extends React.Component {
    state = {
        columns: [{
            title: '角色名称',
            dataIndex: 'name',
            width: 150,
        }, {
            title: '角色标识',
            dataIndex: 'role',
            width: 150,
        },{
            title: '角色描述',
            dataIndex: 'description',
            width: 200,
        },{
            title: '操作',
            key: 'action',
            render: (text, record,index) => (
                <span>
                    <a href="javascript:;" onClick={()=>this.handleUpdate(record)} className="btn-txt-primary">修改</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={()=>this.handleAuth(record)} className="btn-txt-primary">用户授权</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={()=>this.handleAuthDept(record)} className="btn-txt-primary">部门授权</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={()=>this.handleLookAuthUser(record)} className="btn-txt-primary">查看授权用户</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={()=>this.handleLookAuthDept(record)} className="btn-txt-primary">查看授权部门</a>
                    <Divider type="vertical" />
                    <a href="javascript:;" onClick={()=>this.handleDel(record)} className="btn-txt-danger">删除</a>
                </span>
            ),
        }],
        createModal:{
            visible: false,
            confirmLoading: false,
        },
        updateModal:{
            visible: false,
            confirmLoading: false,
        },
        authModal:{
            visible: false,
            confirmLoading: false,
        },
        authUserModal:{
            visible: false,
        },
        authDeptModal:{
            visible: false,
            confirmLoading: false,
        },
        authDeptListModal:{
            visible: false,
        },
    };
    initParams={
        max:10,
        keywords:'',
        page:1,
        state:'',
    }
    componentWillMount(){
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params);
        this.userRequest(); //所有用户请求
        this.deptRequest(); //所有部门请求
        this.apiPermissionRequest(); //所有api权限
    }

    //创建角色
    handleCreate = ()=>{
        this.setState({
            createModal:{
                ...this.state.createModal,
                visible:true
            }
        })
    }
    //创建角色 确定
    handleCreateSubmit = ()=>{
        const _form = this.createForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values);
            values.menus = JSON.stringify(values.menus);
            values.apis = JSON.stringify(values.apis);
            let params = Utils.FilterParam(values);
            console.log(params)
            this.createRequest(params);
        });
    }
    //角色修改
    handleUpdate = (record)=>{
        this.setState({
            updateModal:{
                ...this.state.updateModal,
                visible:true,
                record
            }
        })
    }
    //角色修改 确定
    handleUpdateSubmit = ()=>{
        const _form = this.updateForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values);
            values.menus = JSON.stringify(values.menus);
            let params = Utils.FilterParam(values);
            console.log(params)
            this.updateRequest(params);
        });
    }
    //角色删除
    handleDel = (record)=>{
        Modal.confirm({
            title: '确认删除？',
            content: <div>
                <div>确认删除角色？删除后数据不可恢复！</div>
            </div>,
            okText:'确认',
            cancelText:'取消',
            onOk:()=>{
                let params = {
                    id  :record.id,
                }
                this.delRequest(params);
            }
        })
    }

    //用户授权
    handleAuth = (record)=>{
        this.setState({
            authModal:{
                ...this.state.authModal,
                visible:true,
                record
            }
        })
    }
    //用户授权 确定
    handleAuthSubmit = ()=>{
        const _form = this.authForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values);
            let params = Utils.FilterParam(values);
            //console.log(params)
            this.authRequest(params);

        });
    }
    //查看授权用户
    handleLookAuthUser = (record)=>{
        this.setState({
            authUserModal:{
                visible:true
            }
        })
        let params = {
            roleId:record.id
        }
        this.authUserRequest(params);
    }
    //取消授权（角色移除用户）
    handleCancleAuth =(record)=>{
        console.log(record)
        Modal.confirm({
            title: '确认取消授权？',
            content: <div>
                <div>确认取消授权？取消后该用户不在有该角色权限！</div>
            </div>,
            okText:'确认',
            cancelText:'取消',
            onOk:()=>{
                let params = {
                    roleId :record.roleId ,
                    userId  :record.userId  ,
                }
                this.cancleAuthRequest(params);
            }
        })
    }

    //部门授权
    handleAuthDept = (record)=>{
        this.setState({
            authDeptModal:{
                ...this.state.authDeptModal,
                visible:true,
                record
            }
        })
    }
    //部门授权 确定
    handleAuthDeptSubmit = ()=>{
        const _form = this.deptAuthForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values);
            let params = Utils.FilterParam(values);
            //console.log(params)
           this.deptAuthRequest(params);

        });
    }
    //查看授权部门列表
    handleLookAuthDept = (record)=>{
        this.setState({
            authDeptListModal:{
                visible:true
            }
        })
        let params = {
            roleId:record.id
        }
        this.authDeptRequest(params);
    }
    //取消部门授权（角色移除部门）
    handleCancleDeptAuth =(record)=>{
        console.log(record)
        Modal.confirm({
            title: '确认取消授权？',
            content: <div>
                <div>确认取消授权？取消后该部门不在有该角色权限！</div>
            </div>,
            okText:'确认',
            cancelText:'取消',
            onOk:()=>{
                let params = {
                    roleId:record.roleId ,
                    deptId:record.departmentId,
                }
                this.cancleDeptAuthRequest(params);
            }
        })
    }

    /*角色列表  请求*/
    listRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.get({
            block:'/hr',
            url:'/role',
            params:params,
        }).then((data)=>{
            //console.log(data)
            let page = data.page;
            let dataSource = data.data;
            dataSource.map((item)=>{
                item.key = item.id;
                return item;
            })
            this.setState({
                loading:false,
                dataSource,
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*创建角色请求*/
    createRequest = (params)=>{
        this.setState({
            createModal:{
                ...this.state.createModal,
                confirmLoading: true,
            }
        })
        Axios.post({
            block:'/hr',
            url:'/role',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                createModal:{
                    ...this.state.createModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('创建角色成功！',2,()=>{
                    /*let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    this.listRequest(params);*/
                });
                window.location.reload()
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                createModal:{
                    ...this.state.createModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*修改角色请求*/
    updateRequest = (params)=>{
        this.setState({
            updateModal:{
                ...this.state.updateModal,
                confirmLoading: true,
            }
        })
        Axios.put({
            block:'/hr',
            url:'/role',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                updateModal:{
                    ...this.state.updateModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('修改角色成功！',2,()=>{
                    /*let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    this.listRequest(params);*/
                });
                window.location.reload()
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                updateModal:{
                    ...this.state.updateModal,
                    confirmLoading: false,
                }
            })
        })
    }
    //删除角色
    delRequest = (params) =>{
        this.setState({
            loading:true,
            loadingTxt:'删除中...'
        })
        Axios.delete({
            block:'/hr',
            url:'/role',
            params:params,
        }).then((data)=>{
            console.log(data);
            this.setState({ loading:false })
            message.success('删除成功！',2,()=>{
                this.listRequest(this.initParams);
            });
        }).catch((error)=>{
            this.setState({ loading:false });
            console.log(error);
        })
    }

    /*用户授权(用户添加角色)请求*/
    authRequest = (params)=>{
        this.setState({
            authModal:{
                ...this.state.authModal,
                confirmLoading: true,
            }
        })
        Axios.post({
            block:'/hr',
            url:'/role/userAddRole',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                authModal:{
                    ...this.state.authModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('用户授权成功！',2,()=>{
                    /*let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    this.listRequest(params);*/
                });
                window.location.reload()
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                authModal:{
                    ...this.state.authModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*查询某角色人员列表请求*/
    authUserRequest = (params)=>{
        this.setState({
            loading: true,
            loadingTxt: '加载中...'
        })
        Axios.get({
            block:'/hr',
            url:'/role/queryRoleUsers',
            params:params,
        }).then((data)=>{
            console.log(data)
            let authUserSource = data.data||[];
            authUserSource.map((item)=>{
                item.key = item.id;
                return item;
            })
            this.setState({
                loading: false,
                authUserSource
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                loading: false,
                authUserModal:{
                    visible:false
                }
            })
        })
    }
    //取消授权  （角色移除用户）
    cancleAuthRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'取消授权中...'
        })
        Axios.delete({
            block:'/hr',
            url:'/role/userRemoveRole',
            params:params,
        }).then((data)=>{
            console.log(data);
            this.setState({ loading:false })
            message.success('取消授权成功！',2,()=>{});
            window.location.reload();
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }

    /*部门授权(部门添加角色)请求*/
    deptAuthRequest = (params)=>{
        this.setState({
            authDeptModal:{
                ...this.state.authModal,
                confirmLoading: true,
            }
        })
        Axios.post({
            block:'/hr',
            url:'/role/deptAddRole',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                authDeptModal:{
                    ...this.state.authDeptModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('部门授权成功！',2,()=>{
                    /*let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    this.listRequest(params);*/
                });
                window.location.reload()
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                authDeptModal:{
                    ...this.state.authDeptModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*查询某角色部门列表请求*/
    authDeptRequest = (params)=>{
        this.setState({
            loading: true,
            loadingTxt: '加载中...'
        })
        Axios.get({
            block:'/hr',
            url:'/role/queryRoleDepts',
            params:params,
        }).then((data)=>{
            console.log(data)
            let authDeptSource = data.data||[];
            authDeptSource.map((item)=>{
                item.key = item.id;
                return item;
            })
            this.setState({
                loading: false,
                authDeptSource
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                loading: false,
                authDeptListModal:{
                    visible:false
                }
            })
        })
    }
    //取消部门授权  （角色移除部门）
    cancleDeptAuthRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'取消授权中...'
        })
        Axios.delete({
            block:'/hr',
            url:'/role/deptRemoveRole',
            params:params,
        }).then((data)=>{
            console.log(data);
            this.setState({ loading:false })
            message.success('取消授权成功！',2,()=>{});
            window.location.reload();
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }

    /*所有用户请求*/
    userRequest = ()=>{
        Axios.get({
            block:'/hr',
            url:'/user/allUserSmallInfos',
            params:"",
        }).then((data)=>{
            let users = data.data;
            /*id name userNo*/
            this.setState({
                users,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }
    /*所有部门请求*/
    deptRequest = ()=>{
        Axios.get({
            block:'/hr',
            url:'/department',
            params:"",
        }).then((data)=>{
            //console.log(data)
            let depts = data.data;
            this.setState({
                depts,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }
    //级联查询全部api权限
    apiPermissionRequest = ()=>{
        Axios.get({
            block:'/hr',
            url:'/permission/all',
            params:"",
        }).then((data)=>{
            console.log(data)
            let apiPermission = data.data;
            this.setState({
                apiPermission,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }
    //伸缩列
    components = {
        header: {
            cell:ResizeableTitle
        },
    };
    handleResize = index => (e, { size }) => {
        this.setState(({ columns }) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return { columns: nextColumns };
        });
    };
    render() {
        const columns = this.state.columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        const authUserColumns = [{
                title: '用户名称',
                dataIndex: 'userName',
            },{
                title: '操作',
                key: 'action',
                render: (text, record,index) => (
                    <span>
                        <a href="javascript:;" onClick={()=>this.handleCancleAuth(record)} className="btn-txt-danger">取消授权</a>
                    </span>
                )
            },];
        const authDeptColumns = [{
            title: '部门名称',
            dataIndex: 'departmentName',
        },{
            title: '操作',
            key: 'action',
            render: (text, record,index) => (
                <span>
                        <a href="javascript:;" onClick={()=>this.handleCancleDeptAuth(record)} className="btn-txt-danger">取消授权</a>
                    </span>
            )
        },];
        return (
            <div className="tab-list-box">
                <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                    <Card
                        title="角色列表"
                        bordered={false}
                        extra={<Button type="primary" icon="plus" onClick={this.handleCreate}>创建角色</Button>}
                    >
                        <Table
                            bordered
                            components={this.components}
                            columns={columns}
                            dataSource={this.state.dataSource}
                            pagination={false}
                        />
                    </Card>
                </Spin>
                <Modal title="创建角色"
                       width={650}
                       visible={this.state.createModal.visible}
                       onOk={this.handleCreateSubmit}
                       okText="创建"
                       destroyOnClose = {true}
                       confirmLoading={this.state.createModal.confirmLoading}
                       onCancel={()=>{
                           this.setState({
                               createModal:{
                                   visible:false
                               }
                           })
                       }}
                >
                    <CreateForm
                        apiPermission={this.state.apiPermission}
                        wrappedComponentRef={(createForm)=>{this.createForm = createForm;}}/>
                </Modal>
                <Modal title="修改角色"
                       width={650}
                       visible={this.state.updateModal.visible}
                       onOk={this.handleUpdateSubmit}
                       okText="确定"
                       destroyOnClose = {true}
                       confirmLoading={this.state.updateModal.confirmLoading}
                       onCancel={()=>{
                           this.setState({
                               updateModal:{
                                   visible:false
                               }
                           })
                       }}
                    >
                        <UpdateForm
                            record={this.state.updateModal.record}
                            apiPermission={this.state.apiPermission}
                            wrappedComponentRef={(updateForm)=>{this.updateForm = updateForm;}}/>
                </Modal>
                <Modal title="用户授权"
                       visible={this.state.authModal.visible}
                       onOk={this.handleAuthSubmit}
                       okText="确定"
                       destroyOnClose = {true}
                       confirmLoading={this.state.authModal.confirmLoading}
                       onCancel={()=>{
                           this.setState({
                               authModal:{
                                   visible:false
                               }
                           })
                       }}
                >
                    <AuthForm
                        users={this.state.users}
                        record={this.state.authModal.record}
                        wrappedComponentRef={(authForm)=>{this.authForm = authForm;}}/>
                </Modal>
                <Modal title="授权用户列表"
                       closable={false}
                       visible={this.state.authUserModal.visible}
                       footer={<Button type="primary" onClick={
                           () => {
                               this.setState({
                                   authUserModal: {
                                       visible: false
                                   }
                               })}
                       }>关闭</Button>}
                >
                    <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                        <Table
                            bordered
                            columns={authUserColumns}
                            dataSource={this.state.authUserSource}
                            pagination={false}
                        />
                    </Spin>
                </Modal>
                <Modal title="部门授权"
                       visible={this.state.authDeptModal.visible}
                       onOk={this.handleAuthDeptSubmit}
                       okText="确定"
                       destroyOnClose = {true}
                       confirmLoading={this.state.authDeptModal.confirmLoading}
                       onCancel={()=>{
                           this.setState({
                               authDeptModal:{
                                   visible:false
                               }
                           })
                       }}
                >
                    <DeptAuthForm
                        depts={this.state.depts}
                        record={this.state.authDeptModal.record}
                        wrappedComponentRef={(deptAuthForm)=>{this.deptAuthForm = deptAuthForm;}}/>
                </Modal>
                <Modal title="授权部门列表"
                       closable={false}
                       visible={this.state.authDeptListModal.visible}
                       footer={<Button type="primary" onClick={
                           () => {
                               this.setState({
                                   authDeptListModal: {
                                       visible: false
                                   }
                               })}
                       }>关闭</Button>}
                >
                    <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                        <Table
                            bordered
                            columns={authDeptColumns}
                            dataSource={this.state.authDeptSource}
                            pagination={false}
                        />
                    </Spin>
                </Modal>
            </div>
        );
    }

}
//创建角色表单
class CreateForm extends React.Component{
    state = {}

    handleChangeName = (e)=>{
        this.props.form.setFieldsValue({
            'role':e.target.value,
        });
    }
    //勾选目录操作
    handleCheck = (checkedKeys) => {
       /* console.log('onCheck', checkedKeys);
        this.setState({ checkedKeys });*/
        if(checkedKeys.length){
            this.props.form.setFieldsValue({
                'menus':checkedKeys,
            });
        }else {
            this.props.form.setFieldsValue({
                'menus':null,
            });
        }
    }
    //勾选权限
    handlePermsCheck = (checkedKeys)=>{
        console.log(checkedKeys)
        if(checkedKeys.length){
            this.props.form.setFieldsValue({
                'apis':checkedKeys,
            });
        }else {
            this.props.form.setFieldsValue({
                'apis':null,
            });
        }
    }
    //渲染目录结构
    renderTreeNodes = data => data.map((item) => {
        if (item.children) {
            return (
                <TreeNode title={item.title} key={item.key} dataRef={item}>
                    {this.renderTreeNodes(item.children)}
                </TreeNode>
            );
        }
        return <TreeNode {...item} disabled={item.key=="/home"?true:false}/>;
    })
    //渲染权限结构
    renderPermsTreeNodes = data => data.map((item) => {
        if (item.childs&&item.childs.length) {
            return (
                <TreeNode title={item.name} key={item.id} dataRef={item}>
                    {this.renderPermsTreeNodes(item.childs)}
                </TreeNode>
            );
        }
        return <TreeNode title={item.name} key={item.id} dataRef={item}/>;
    })
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const apiPermission = this.props.apiPermission||[];
        return (
            <Form>
                <FormItem label="名称" {...formItemLayout}>
                    {
                        getFieldDecorator('name',{
                            rules: [{ required: true, message: '请填写名称!' }],
                        })(
                            <Input type="text" placeholder="名称" onChange={this.handleChangeName}/>
                        )
                    }
                </FormItem>
                <FormItem label="角色标识" {...formItemLayout}>
                    {
                        getFieldDecorator('role',{
                            rules: [{ required: true, message: '请填写角色标识!' }],
                        })(
                            <Input type="text" placeholder="角色标识"/>
                        )
                    }
                </FormItem>
                <FormItem label="角色描述" {...formItemLayout}>
                    {
                        getFieldDecorator('description',{
                        })(
                            <TextArea placeholder="角色标识" autosize/>
                        )
                    }
                </FormItem>
                <FormItem label="系统菜单权限" {...formItemLayout}>
                    {
                        getFieldDecorator('menus',{
                            rules: [{ required: true, message: '请选择系统菜单权限!' }],
                            initialValue:["/home"]
                        })(
                            <div>
                                <Input type="hidden"/>
                                <Tree
                                    checkable
                                    defaultCheckedKeys={['/home']}
                                    onCheck={this.handleCheck}
                                >
                                    <TreeNode title="所有权限" key="all_permission">
                                        {this.renderTreeNodes(menuConfig)}
                                    </TreeNode>
                                </Tree>
                            </div>
                        )
                    }
                </FormItem>
                <FormItem label="接口权限" {...formItemLayout}>
                    {
                        getFieldDecorator('apis',{
                            rules: [{ required: true, message: '请选择接口权限权限!' }],
                        })(
                            <div>
                                <Input type="hidden"/>
                                <Tree
                                    checkable
                                    onCheck={this.handlePermsCheck}
                                >
                                    {/*<TreeNode title="所有权限" key="all_permission">*/}
                                        {this.renderPermsTreeNodes(apiPermission)}
                                   {/* </TreeNode>*/}
                                </Tree>
                            </div>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
CreateForm = Form.create({})(CreateForm);
//修改角色表单
class UpdateForm extends React.Component{
    state = {}

    handleChangeName = (e)=>{
        this.props.form.setFieldsValue({
            'role':e.target.value,
        });
    }
    //勾选目录操作
    handleCheck = (checkedKeys) => {
        /* console.log('onCheck', checkedKeys);
         this.setState({ checkedKeys });*/
        if(checkedKeys.length){
            this.props.form.setFieldsValue({
                'menus':checkedKeys,
            });
        }else {
            this.props.form.setFieldsValue({
                'menus':null,
            });
        }
    }
    //勾选权限
    handlePermsCheck = (checkedKeys)=>{
        console.log(checkedKeys)
        if(checkedKeys.length){
            this.props.form.setFieldsValue({
                'apis':checkedKeys,
            });
        }else {
            this.props.form.setFieldsValue({
                'apis':null,
            });
        }
    }
    //渲染目录结构
    renderTreeNodes = data => data.map((item) => {
        if(!item.hidden){
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.path} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} key={item.path} disabled={item.path=="/home"?true:false}/>;
        }
    })
    //渲染权限结构
    renderPermsTreeNodes = data => data.map((item) => {
        if (item.childs&&item.childs.length) {
            return (
                <TreeNode title={item.name} key={item.id} dataRef={item}>
                    {this.renderPermsTreeNodes(item.childs)}
                </TreeNode>
            );
        }
        return <TreeNode title={item.name} key={item.id} dataRef={item}/>;
    })
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const record = this.props.record||{};
        const menus = record.menus?JSON.parse(record.menus):[];
        const apis = record.apis?JSON.parse(record.apis):[];
        const apiPermission = this.props.apiPermission||[];
        //console.log(record)
        //console.log(menus)
        return (
            <Form>
                <FormItem label="id" {...formItemLayout} style={{display:"none"}}>
                    {
                        getFieldDecorator('id',{
                            initialValue:record.id
                        })(
                            <Input type="text"/>
                        )
                    }
                </FormItem>
                <FormItem label="名称" {...formItemLayout}>
                    {
                        getFieldDecorator('name',{
                            rules: [{ required: true, message: '请填写名称!' }],
                            initialValue:record.name
                        })(
                            <Input type="text" placeholder="名称" onChange={this.handleChangeName}/>
                        )
                    }
                </FormItem>
                <FormItem label="角色标识" {...formItemLayout}>
                    {
                        getFieldDecorator('role',{
                            rules: [{ required: true, message: '请填写角色标识!' }],
                            initialValue:record.role
                        })(
                            <Input type="text" placeholder="角色标识"/>
                        )
                    }
                </FormItem>
                <FormItem label="角色描述" {...formItemLayout}>
                    {
                        getFieldDecorator('description',{
                            initialValue:record.description
                        })(
                            <TextArea placeholder="角色标识" autosize/>
                        )
                    }
                </FormItem>
                <FormItem label="系统菜单权限" {...formItemLayout}>
                    {
                        getFieldDecorator('menus',{
                            rules: [{ required: true, message: '请填写系统菜单权限!' }],
                            initialValue:menus
                        })(
                            <div>
                                <Input type="hidden"/>
                                <Tree
                                    checkable
                                    defaultCheckedKeys={menus}
                                    onCheck={this.handleCheck}
                                >
                                    <TreeNode title="所有权限" key="all_permission">
                                        {this.renderTreeNodes(menuConfig)}
                                    </TreeNode>
                                </Tree>
                            </div>
                        )
                    }
                </FormItem>
                <FormItem label="接口权限" {...formItemLayout}>
                    {
                        getFieldDecorator('apis',{
                            rules: [{ required: true, message: '请选择接口权限权限!' }],
                            initialValue:apis
                        })(
                            <div>
                                <Input type="hidden"/>
                                <Tree
                                    checkable
                                    defaultCheckedKeys={apis}
                                    onCheck={this.handlePermsCheck}
                                >
                                    {/*<TreeNode title="所有权限" key="all_permission">*/}
                                        {this.renderPermsTreeNodes(apiPermission)}
                                   {/* </TreeNode>*/}
                                </Tree>
                            </div>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
UpdateForm = Form.create({})(UpdateForm);

//用户授权 表单
class AuthForm extends React.Component{
    state = {}

    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const record = this.props.record||{};
        const users = this.props.users||[];
        const usersOptions = users.map((item)=>{
            return <Option key={item.id} value={item.id}>{item.name}</Option>
        })
        return (
            <Form>
                <FormItem label="角色" {...formItemLayout} style={{display:"none"}}>
                    {
                        getFieldDecorator('roleId',{
                           initialValue:record.id
                        })(
                            <Input type="text" placeholder="名称"/>
                        )
                    }
                </FormItem>
                <div style={{textAlign:"center",marginBottom:15}}>{record.name} 添加用户</div>
                <FormItem label="用户" {...formItemLayout}>
                    {
                        getFieldDecorator('userId', {
                            rules: [{ required: true, message: '请选择用户!' }],
                        })(
                            <Select
                                placeholder="请选择用户"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >
                                {usersOptions}
                            </Select>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
AuthForm = Form.create({})(AuthForm);

//部门授权 表单
class DeptAuthForm extends React.Component{
    state = {}

    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const record = this.props.record||{};
        const depts = this.props.depts||[];
        const deptsOptions = depts.map((item)=>{
            return <Option key={item.id} value={item.id}>{item.name}</Option>
        })
        return (
            <Form>
                <FormItem label="角色" {...formItemLayout} style={{display:"none"}}>
                    {
                        getFieldDecorator('roleId',{
                            initialValue:record.id
                        })(
                            <Input type="text" placeholder="名称"/>
                        )
                    }
                </FormItem>
                <div style={{textAlign:"center",marginBottom:15}}>{record.name} 添加部门</div>
                <FormItem label="部门" {...formItemLayout}>
                    {
                        getFieldDecorator('deptId', {
                            rules: [{ required: true, message: '请选择部门!' }],
                        })(
                            <Select
                                placeholder="请选择部门"
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >
                                {deptsOptions}
                            </Select>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
DeptAuthForm = Form.create({})(DeptAuthForm);
